<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { ElMessage } from 'element-plus'
import { toolbars } from './defaultOptions'
import httpRequest from '~/utils/request'

export default {
  components: { MavonEditor: mavonEditor },
  props: {
    value: {
      type: String,
      default: '',
    },
    editable: {
      type: Boolean,
      default: true,
    },
    toolbarsFlag: {
      type: Boolean,
      default: true,
    },
    subfield: {
      type: Boolean,
      default: false,
    },
    defaultOpen: {
      type: String,
      default: 'edit',
    },
    deleteOption: {
      type: Object,
      default: () => {
        return {
          isShow: false,
          data: {},
        }
      },
    },
  },
  data() {
    return {
      toolbars,
      editorValue: '',
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.editorValue = newVal
      },
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    change(value, render) {
      this.$emit('change', value, render)
    },
    setImg(imgArr) {
      imgArr.forEach((row) => {
        this.$refs.editorRef.$refs.toolbar_left.$imgAddByFilename(
          // markdown模板图片地址
          row.id,
          {
            // 图片控制列表图片链接
            miniurl: row.id,
            // 图片控制列表名字
            name: row.text,
            // markdown模板图片名称
            _name: row.text,
          },
        )
      })
    },

    imgDel(_file) {
      // console.log(_file);
    },
    // 绑定@imgAdd event
    imgAdd(position, imgfile) {
      const url = '' //上传文件地址
      const formData = new FormData()
      formData.append('file', imgfile)
      httpRequest
        .post(`${url}`, formData)
        .then((res) => {
          if (res.success) {
            const path = res.data // 图片访问路径
            this.$refs.editorRef.$img2Url(position, path)
          }
          else {
            ElMessage.error(res.msg)
          }
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    },
    handleDelete() {
      this.$emit('delete', this.deleteOption.data)
    },
  },
}
</script>

<template>
  <MavonEditor
    ref="editorRef"
    v-model="editorValue"
    style="height: 100%"
    :toolbars-flag="toolbarsFlag"
    :default-open="defaultOpen"
    :subfield="subfield"
    :toolbars="toolbars"
    :editable="editable"
    class="mavon-editor-container"
    @change="change"
    @img-add="imgAdd"
    @img-del="imgDel"
  >
    <template #right-toolbar-after>
      <el-button v-if="deleteOption.isShow" link class="op-icon" style="margin-bottom: 8px; margin-top: 3px;" title="删除" @click="handleDelete">
        <span class="custom-icon">✖</span>
      </el-button>
    </template>
  </MavonEditor>
</template>

<style lang="scss" scoped>
.mavon-editor-container :deep() ol {
  list-style: auto;
}

.mavon-editor-container :deep() ul {
  list-style: disc;
}

.custom-icon {
  font-size: 16px;
}
</style>
